﻿using System;
using System.IO;
using System.Linq;
using System.Web;

namespace Otgruzka.Export
{
    static public class ExcelLoader
    {
        const string ReportFolder = @"~\App_Data\Excel";
        const string ReportNameTmpl = @"~\App_Data\Excel\{0}.xml";
        const int ExpiresInMinutes = 5;

        static public Guid SaveReport(HttpContext context, Guid reportID, string xml)
        {
            using (var stream = File.CreateText(getFileName(context, reportID.ToString())))
                stream.Write(xml);
            return reportID;
        }
        static public void WriteFile(HttpContext context, string ReportID)
        {
            var fileName = getFileName(context, ReportID);
            if (!File.Exists(fileName))
                throw new Exception("Файл не найден");
            context.Response.WriteFile(fileName);
        }
        static public void RemoveOldFiles()
        {
            foreach (var fileName in Directory.GetFiles(ReportFolder).Where(fileName => isExpired(File.GetCreationTime(fileName))))
                File.Delete(fileName);
        }

        static private string getFileName(HttpContext context, string reportID)
        {
            return context.Server.MapPath(string.Format(ReportNameTmpl, reportID));
        }
        static private bool isExpired(DateTime created)
        {
            return Math.Abs((DateTime.Now - created).TotalMinutes) >= ExpiresInMinutes;
        }
    }
}